from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

from user.models import Book,Hero,Area


# Create your views here.
def index(request):
    return HttpResponse('hello python')

def mytemp(request):
    context = {}
    context['hello'] = "hello world"
    context['href'] = "<a href='http://www.baidu.com'>点击跳转</a>"
    return render(request,'hello.html',context)

def book(request):
    b = Book.objects.get(id=1)
    # b.hero_set.all()   获取书籍id为1中所有的英雄人物信息

    h = Hero.objects.get(id=1)
    print(h.book.name) # h.book 获取英雄id为1的书籍信息

    return HttpResponse([x.name for x in b.hero_set.all()])

"""
自查询
"""
def area(request): 
    # 获取广州市的上级地区和下级地区
    area = Area.objects.get(title='广州市')
    # 上级地区
    parent = area.parent
    # 下级地区
    childs = area.area_set.all()
    return render(request,'area.html',{'parent':parent.title,'childs':childs})

def child(request):
    return render(request,'child.html')

from django.core.paginator import Paginator
def show_area(request,pindex):
    # 展示 省级地区
    arealist = Area.objects.filter(parent__isnull = True)
    pagintor = Paginator(arealist,10)

    if pindex == "":
        pindex = 1

    page = pagintor.page(pindex)

    print(page.has_previous)

    return render(request,'show_area.html',{"arealist":page})


def city_select(request):
    return render(request,'省市联动.html')
def get_prov(request):
    provlist = Area.objects.filter(parent__isnull=True)
    areas = []
    for area in provlist:
        areas.append((area.id,area.title))
    return JsonResponse({"data":areas})
def child_city(request):
    id = request.GET.get('id')
    citylist = Area.objects.filter(parent=id)
    areas = []
    for area in citylist:
        areas.append((area.id,area.title))
    return JsonResponse({"data":areas})

    